//
//  AudioPlayerHelper.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/29.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "AudioPlayerHelper.h"
#import <AVFoundation/AVFoundation.h>

@interface AudioPlayerHelper ()<AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, strong) void(^audioPlayDidFinished)(NSString *path);

@end
@implementation AudioPlayerHelper

+ (instancetype)helper {
    static AudioPlayerHelper *audioPlayerHelper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioPlayerHelper = [[AudioPlayerHelper alloc] init];
    });
    return audioPlayerHelper;
}

- (void)playAudioWithPath:(NSString *)path finished:(void (^)(NSString * _Nonnull))finished {
    if (self.player.isPlaying == YES && self.audioPlayDidFinished != nil) {
//        self.audioPlayDidFinished(self.player.url.path);
        [self.player stop];
        self.player = nil;
    }
    
    AVAudioSession * session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    
    
    self.audioPlayDidFinished = finished;
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:path.fileToURL error:nil];
    self.player.volume = 1;
    self.player.delegate = self;
    [self.player prepareToPlay];
    [self.player play];
    

}
- (void)stopAudioPlay {
    [self.player stop];
    self.player = nil;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    if (self.audioPlayDidFinished) {
        self.audioPlayDidFinished(player.url.path);
    }
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    
}

@end
